
package com;

import java.io.*;
import java.util.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.*;
import excel.Excel;


public class Jd {
	
	/*Property File Variables*/
	String searchQuery = "";
	String city = "";
	String name = "";
	String email = "";
	String subject = "";
	String body = "";
	int maxEmail;
	int maxCount;
	int pageEnd;
	int pageStart;
	long mobile;
	
	/* URL maintaining variables */
	String baseURL = "";
	String refURL = "";
	
	/* Company Detail maintaining variables */
	String companyEmail="";
	String companyAddress="";
	String companyNumber="";
	String companyName="";
	
	/* Wait time providing variables */
	int modular;
	int minimum;
	
	/* Execution controlling variables*/
	int currentEmail;
	int j;
	int count;
	
	/* File handling variable */
	Excel excel;
	
	/* Browser */
	WebDriver driver;
	
	/* Random number generating variable */
	Random rn = new Random();
	
	/* Properties file variable */
	Properties props = new Properties();
	
	/**
	 * Assignment to the variables and extraction of information
	 * from property file before executing the logic.
	 */
	@BeforeClass
	public void initialize() throws Exception{
        
		FileInputStream config = new FileInputStream("config.properties");
        props.load(config);
        searchQuery = props.getProperty("searchQuery");
        city = props.getProperty("city");
        name = props.getProperty("name"); 
        mobile = Long.parseLong(props.getProperty("mobile"));
        email = props.getProperty("email1");
        subject = props.getProperty("subject");
        body = props.getProperty("body");
        pageStart = Integer.parseInt(props.getProperty("pageStart"));
        pageEnd = Integer.parseInt(props.getProperty("pageEnd"));
        maxCount = Integer.parseInt(props.getProperty("maxCount")); /* Maximum times email and mobile can be used */
        maxEmail = Integer.parseInt(props.getProperty("maxEmail")); /* Maximum number of that can be used */
        minimum = 2;
		modular = 4;
        currentEmail = 1;
		count = 1;
		baseURL = "http://www.justdial.com/";
		excel = new Excel();
	}
	
	/*
	 * Selects city enter the query and finally click on the go button
	 */
	@Test(priority = 0)
	public void openSite() throws InterruptedException {
		
		driver = new FirefoxDriver();
		driver.get(baseURL);
		Thread.sleep((waitTime()) * 1000);
		WebElement searchValue = driver.findElement(By.id("what"));
		WebElement cityLnk = driver.findElement(By.id("ctlnk"));
		WebElement cityValue = driver.findElement(By.id("city"));
		WebElement goButton = driver.findElement(By.id("go"));
		cityLnk.click();
		cityValue.sendKeys(city);
		Thread.sleep((waitTime()) * 1000);
		WebElement citySelect = driver.findElement(By.id("undefined-undefined-0"));
		citySelect.click();
		searchValue.sendKeys(searchQuery);
		goButton.click();
		refURL = driver.getCurrentUrl();
		refURL = refURL + "/page-";
		baseURL = refURL + pageStart;
		driver.get(baseURL);
		
	}
	
	/*
	 * It provides a sleeping time for thread
	 */
	public long waitTime() {
		
		long time = rn.nextInt() % modular;
		if( time < 0 )
			time = time * -1;
		time = time + minimum;
		return time;
		
	}
	
	/*
	 * It launches browser selects the page.
	 * Go to all the company one by one listed in the page and fill their corresponding forms
	 * After filling all forms of current page it changes the page URL for next page
	 */
	@Test(priority = 1)
	public void selectPageAndCompany() throws Exception {
		
		List<WebElement> carPartsCompanyList = driver.findElements(By.linkText("SMS / Email"));
		carPartsCompanyList = driver.findElements(By.linkText("SMS / Email"));
		while(pageStart <= pageEnd) {
			
			for(j=0 ; j < carPartsCompanyList.size(); j = j + 1) {
				
				String companyPageLink = carPartsCompanyList.get(j).getAttribute("href");
				companyPageLink = companyPageLink.substring(0, companyPageLink.length()-3);
				driver.get(companyPageLink);
				System.out.println("Page:" + pageStart + " j:" + j);
				extractData();
				fillEnquiryForm();
				//fillSmsEmailForm();
				driver.navigate().back();
				Thread.sleep(2000);
				carPartsCompanyList = driver.findElements(By.linkText("SMS / Email"));
				/*if(count == maxCount) {
					
					if( !getNewValues()) {
						return;
					}
					count = 1;
					
				} else {
					count = count + 1;
				}*/
			}
			if(j == 25) {
				
				pageStart = pageStart + 1;
				baseURL = refURL + pageStart;
				driver.get(baseURL);
				carPartsCompanyList = driver.findElements(By.linkText("SMS / Email"));
			
			} else {
				pageStart = 0;
			}
			Thread.sleep((waitTime() - minimum + 1) * 1000 * 60);
			
		}
		
	}
	
	/*
	 * Extract the details of shop
	 */
	public void extractData() throws Exception {
		
		int i;
		String buffer1;
		companyNumber = "";
		companyAddress = "";
		WebElement name = driver.findElement(By.className("fn"));
		WebElement address = driver.findElement(By.className("text"));
		List<WebElement> number = driver.findElements(By.className("text"));
		buffer1 = address.getText();
		for( i = 0; i < buffer1.length() ;i = i + 1) {
			if(buffer1.charAt(i) == '|') {
				break;
			}
			companyAddress = companyAddress + buffer1.charAt(i);
		}
		companyName = name.getText();
		i=1;
		while( (i + 1) < number.size()) {
			companyNumber = number.get(i).getText() + ", " + companyNumber;
			i = i + 1;
		}
		List<WebElement> check = driver.findElements(By.linkText("Send Enquiry by Email"));
		if(check.size() == 0) {
			companyNumber = number.get(i).getText() + ", " + companyNumber;
		}
		if(companyNumber.length() > 2)
		companyNumber = companyNumber.substring(0, companyNumber.length()-3);
		excel.insertRow(companyName, companyAddress, companyNumber);
	}
	
	/*
	 * This function opens enquiry form, fills the form and then finally submits the form
	 */
	public void fillEnquiryForm() throws InterruptedException {
		
		List<WebElement> form = driver.findElements(By.linkText("Send Enquiry by Email"));
		if(form.size() == 0)
			return;
		form.get(0).click();
		WebElement formName = driver.findElement(By.id("enqname"));
		WebElement formMobile = driver.findElement(By.id("enqmobile"));
		WebElement formEmail = driver.findElement(By.id("enqemail"));
		WebElement formSubject = driver.findElement(By.id("enqsub"));
		WebElement formBody = driver.findElement(By.id("enqbd"));
		List<WebElement> formButton = driver.findElements(By.className("jbtn"));
		formName.clear();
		formName.sendKeys(name);
		formMobile.clear();
		formMobile.sendKeys(String.valueOf(mobile));
		formEmail.clear();
		formEmail.sendKeys(email);
		formSubject.clear();
		formSubject.sendKeys(subject);
		formBody.clear();
		formBody.sendKeys(body);
		formButton.get(formButton.size() - 1).click();
		Thread.sleep((waitTime()) * 1000);
		
	}
	
	/*
	* This function opens enquiry form, fills the form and then finally submits the form
	*/
	public void fillSmsEmailForm() throws InterruptedException {
		
		List<WebElement> smsEmail = driver.findElements(By.linkText("SMS / Email"));
		if(smsEmail.size() == 0)
			return;
		smsEmail.get(0).click();
		List<WebElement> formButton = driver.findElements(By.className("jbtn"));
		WebElement formName = driver.findElement(By.id("ibse_name"));
		WebElement formMobile = driver.findElement(By.id("ibse_mobile"));
		WebElement formEmail = driver.findElement(By.id("ibse_email"));
		formName.clear();
		formName.sendKeys(name);
		formMobile.clear();
		formMobile.sendKeys(String.valueOf(mobile));
		formEmail.clear();
		formEmail.sendKeys(email);
		formButton.get(formButton.size() - 1).click();
		Thread.sleep((waitTime()) * 1000);
		
	}

	
	/*
	 *It provides new values to execute 
	 */
	public boolean getNewValues() {
		
		currentEmail = currentEmail + 1;
		if(currentEmail > maxEmail) {
			return false;
		}
		email = props.getProperty("email"+currentEmail);
		mobile = mobile + 1;
		return true;
		
	}
	
	/*
	 * closes the execl and close the browser
	 */
	@Test(priority = 2)
	public void distructor() throws Exception {
		Thread.sleep(waitTime() * 1000);
		excel.closeWorkbook();
		driver.close();
	}
}
